package com.ng.desktop.view.alimento;

import javax.swing.JOptionPane;

import com.ng.desktop.model.Alimento;
import com.ng.desktop.model.Receta;
import com.ng.desktop.persistence.AlimentoPersistence;
import com.ng.desktop.persistence.RecetaPersistence;
import com.ng.desktop.services.NGFactoryBean;
import com.ng.framework.persistence.NGSearchCriteria;
import com.ng.framework.persistence.NGSearchParameter;
import com.ng.framework.persistence.NGSearchParameter.Type;
import com.ng.framework.persistence.NGSearchParameter.UnaryOperation;
import com.ng.framework.view.desktop.NGTablePanel;

public class AlimentoTablePanel extends NGTablePanel<Alimento, AlimentoPersistence> {

	private static final long serialVersionUID = -5930751801921847448L;

	private RecetaPersistence recetaPersistence;

	public AlimentoTablePanel(AlimentoPersistence persistence) {
		super(persistence);
	}

	@Override
	protected String[] getColumnNames() {
		return new String[]{"Id", "Nombre", "Categoría", "Tamaño de Porción"};
	}

	@Override
	protected int[] getColumnWidths() {
		return new int[]{70, 165, 165, 155};
	}

	@Override
	protected Object[] toRow(Alimento alimento) {
		return new Object[]{alimento.getId(), alimento.getNombre(), alimento.getCategoria().getNombre(),
				alimento.getCantidadFraccion() + " " + alimento.getUnidadMedida().getNombre()};
	}

	@Override
	protected boolean create(AlimentoPersistence persistence) {
		AlimentoEditDialog dialog = new AlimentoEditDialog(JOptionPane.getFrameForComponent(this), persistence);
		dialog.setLocationRelativeTo(this);
		dialog.setVisible(true);
		return true;
	}

	@Override
	protected boolean edit(AlimentoPersistence persistence, Alimento instance) {
		AlimentoEditDialog dialog = new AlimentoEditDialog(JOptionPane.getFrameForComponent(this), persistence, instance);
		dialog.setLocationRelativeTo(this);
		dialog.setVisible(true);
		return true;
	}

	@Override
	protected Alimento getSelectedInstance(AlimentoPersistence persistence, Object[] rowData) {
		return persistence.findById((Long) rowData[0]);
	}

	@Override
	protected boolean esBorrable(Alimento alimento) {
		NGSearchCriteria searchCriteria = new NGSearchCriteria();
		searchCriteria.addNGSearchParameter(new NGSearchParameter(Receta.class, "alimentos", String.valueOf(alimento.getId()),
				Type.INTEGER, UnaryOperation.EQUALS, true, "id"));

		boolean borrar = this.getRecetaPersistence().getAll(searchCriteria).size() == 0;

		if (!borrar) {
			JOptionPane.showMessageDialog(JOptionPane.getFrameForComponent(this),
					"El alimento seleccionado no se puede borrar ya que se encuentra asociada a una o mas recetas.", "Error",
					JOptionPane.ERROR_MESSAGE);
		}

		return borrar;
	}

	private RecetaPersistence getRecetaPersistence() {
		if (recetaPersistence == null) {
			recetaPersistence = (RecetaPersistence) NGFactoryBean.getInstance().getBean("recetaPersistence");
		}

		return recetaPersistence;
	}
}
